package com.qiyadeng.wechat.roo.model;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.joda.time.DateTime;
import org.springframework.roo.addon.dbre.RooDbManaged;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;

@RooJavaBean
@RooToString
@RooJpaActiveRecord(versionField = "", table = "SMS_RECORD")
@RooDbManaged(automaticallyDelete = true)
public class SmsRecord {
	
	//根据手机号码找到最新的验证信息
	public static SmsRecord getLastestSmsByPhone(String phone){
		String type="CHECKCODE";
		DateTime now = new DateTime(new Date());
		DateTime yesterday = now.minusDays(1);
		Calendar c = Calendar.getInstance();
		c.setTime(yesterday.toDate());
		List<SmsRecord> smsList = entityManager().createQuery("SELECT o FROM SmsRecord o where o.createTime>?1 and o.type=?2 and o.phone=?3 order by o.createTime desc", SmsRecord.class)
						.setMaxResults(1)
						.setParameter(1, c)
						.setParameter(2, type)
						.setParameter(3, phone)
						.getResultList();
		if(smsList.size()>0){
			return smsList.get(0);
		}
		return null;
	}
	
	public static Long getCountSms(String phone){
		String type="CHECKCODE";
		DateTime now = new DateTime(new Date());
		DateTime yesterday = now.minusDays(1);
		Calendar c = Calendar.getInstance();
		c.setTime(yesterday.toDate());
		Long l = entityManager().createQuery("SELECT count(o) FROM SmsRecord o where o.createTime>?1 and o.type=?2 and o.phone=?3 order by o.createTime desc", Long.class)
						.setMaxResults(1)
						.setParameter(1, c)
						.setParameter(2, type)
						.setParameter(3, phone)
						.getSingleResult();
		
		return l;
	}
	
	//保存验证短信内容
	public static void saveSms(String phone, String content){
		String type="CHECKCODE";
		/*DateTime now = new DateTime(new Date());
		DateTime yesterday = now.minusMinutes(2);
		Calendar c = Calendar.getInstance();
		c.setTime(yesterday.toDate());
		
		List<SmsRecord> smsList = entityManager().createQuery("select o from SmsRecord o where o.createTime>?1 and o.type=?2 and o.phone=?3", SmsRecord.class)
		.setParameter(1, c)
		.setParameter(2, type)
		.setParameter(3, phone)
		.getResultList();
		
		if(smsList.size()>0){
			return;
		}*/
		
		SmsRecord smsRecord = new SmsRecord();
		smsRecord.setPhone(phone);
		smsRecord.setCreateTime(Calendar.getInstance());
		smsRecord.setType(type);
		smsRecord.setContent(content);
		smsRecord.persist();
	}
}
